<template>
  <base-breadcrumb :title="$route.meta.title" :breadcrumb="!isAudit">
    <!-- 实测实量方案、样板引路实施方案、编制品质工程六项专项治理方案----的新增、编辑、查看 -->
    <a-form-model
      ref="ruleForm"
      :model="form"
      :label-col="{ span: 6 }"
      :wrapper-col="{ span: 18 }"
      :rules="editModel != 0 ? rules : {}"
      id="base-breadcrumb"
      style="position: relative"
    >
      <a-spin :spinning="loading.DRAFT || loading.SUBMITTED">
        <!-- 基本信息 -->
        <a-card :bordered="false" style="margin-bottom: 46px">
          <title-name title="基本信息"></title-name>
          <custom-form  ref="form"  :formList="formList" :isEmit="false" :form="form" :editModel="editModel == 0 ? 'V' : ''" @getProjectInfo="getAuditProjectList" @selectOrg="selectOrg">
          </custom-form>
          <title-name title="相关附件" />
          <BTableUpload v-model="form.fileArrays" :disabled="editModel == 0" business-code="QM04" />
        </a-card>
      </a-spin>
      <!-- 页脚操作栏 -->
      <div v-if="!isConsultation" class="btn_box tool-btns--fixed page-btn-right-top">
        <a-button
          :loading="loading.DRAFT"
          :disabled="loading.SUBMITTED"
          v-if="(editModel == 1 && (statusCode === 'DRAFT' || statusCode === 'REJECTED')) || editModel == 2"
          type="primary"
          class="button_right"
          @click="handleSubmit('DRAFT')"
          >{{
            statusCode === 'PAST' || statusCode === 'REJECTED' || form.changeVersion > 1 ? '保存' : '保存草稿'
          }}</a-button
        >
        <a-button
          :loading="loading.SUBMITTED"
          :disabled="loading.DRAFT"
          v-if="
            (editModel == 1 && (statusCode === 'DRAFT' || statusCode === 'REJECTED')) ||
            editModel == 2 ||
            (editModel != 0 && statusCode === 'PAST')
          "
          type="primary"
          class="button_right"
          @click="handleSubmit('SUBMITTED')"
          >提交</a-button
        >
        <a-button v-if="checkVisibleInDetail" type="primary" @click="handleActiveClose">关闭</a-button>
      </div>
    </a-form-model>
    <selectApprover :businessId="businessId"  :processConfig="setProcessConfig"></selectApprover>
  </base-breadcrumb>
</template>

<script>
import { planBusinessBase } from '@/api/quality/quality' // api
import BaseEditPage from '@/views/baseEditPage' // 编辑详情页基础配置
import SelectSubCompany from '@/components/Select/SelectSubCompany' // 分公司
import SelectProject from '@/components/Select/SelectProject' // 项目名称
import SelectStaffWithTooltip from '@/components/Select/SelectStaffWithTooltip'
import BTableUpload from '@/components/BComponents/BTableUpload'
import Selector from '@/components/Select/Selector'

export default {
  name: 'a' + Date.now(),
  extends: new BaseEditPage(),
  components: {
    BTableUpload
  },
  props: {
    // 是否作为审批详情
    isAudit: {
      type: Boolean,
      default: false
    },
    // 是否作为意见征询
    isConsultation: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      loading: { DRAFT: false, SUBMITTED: false }, // 草稿和提交按钮loding
      editModel: 0, // 操作状态:0 查看;1 编辑;2 新增
      id: '', // 业务id
      historyId: '', // 履历id
      projectDeptId: '', // 项目组织id
      form: {
        branchComId: void 0,
        createTime: void 0,
        filler: void 0,
        fileArrays: [],
        branchPname: ''
      },
      statusCode: '', // 审批状态
      rules: {
        branchComId: [{ required: true, message: '请选择分公司', trigger: 'change' }],
        projectId: [{ required: true, message: '请选择项目', trigger: 'change' }],
        editEmployee: [{ required: true, message: '请选择编制人', trigger: 'change' }],
        editDate: [{ required: true, message: '请选择编制时间', trigger: 'change' }],
        planTypeId: [{ required: true, message: '请选择方案类别', trigger: 'change' }],
        textPage: [{ required: true, message: '请填写正文页数', trigger: 'change' }],
        attachPage: [{ required: true, message: '请填写附页页数', trigger: 'change' }],
        describes: [{ required: true, message: '请填写版本描述', trigger: 'change' }]
      },
      //获取流程配置值
      processConfig: null,
      //点击提交发送流程配置值
      setProcessConfig: null,
      businessId: null
    }
  },
 async mounted() {
    this.init()
    // let processConfigKey = this.getPriceByName(this.programmeType)
    // //获取通过获取流程配置值
    // this.processConfig = await this.$getConfigFn(processConfigKey)
  },
  computed: {
    // 表单列表
    formList() {
      return [
        {
          type: "orgTree",
          keyName: 'projectId',
          label: '所属单位',
          isNeedAuth: true,
          isAutoSelectFirst: this.editModel == 2,
          span: this.editModel == 0 ? 8 : 16,
          isNoBorder: this.editModel == 0,
          viewName: "branchPname",
          checkStrictly: true,
        },
        // {
        //   type: SelectSubCompany,
        //   keyName: 'branchComId',
        //   label: '所属分公司',
        //   viewName: 'branchComName',
        //   attrs: {
        //     autoSelected: this.editModel == 2
        //   }
        // },
        // {
        //   type: SelectProject,
        //   keyName: 'projectId',
        //   label: '所属项目',
        //   viewName: 'projectName',
        //   attrs: {
        //     keyValue: 'branchComId',
        //     autoSelected: this.editModel == 2,
        //     isClear: this.editModel == 2,
        //     form: this.form
        //   },
        //   selectChange: (e) => {
        //     this.projectDeptId = e?.projectDeptId
        //   }
        // },
        {
          type: SelectStaffWithTooltip,
          keyName: 'editEmployee',
          viewName: 'editName',
          label: '编制人',
          attrs: {
            rootOrgId: this.projectDeptId,
            isInit: false,
            labelInValue: true,
            showSearch: true
          },
          getOption: (e) => {
            this.$set(this.form, 'editEmployeeId', e?.[0]?.userId)
            this.$set(this.form, 'editName', e?.[0]?.name)
          }
        },
        {
          keyName: 'editDate',
          type: 'a-date-picker',
          placeholder: '请选择日期',
          label: '编制时间',
          attrs: {
            valueFormat: 'YYYY-MM-DD'
          }
        },
        {
          keyName: 'filler',
          type: 'a-input',
          disabled: true,
          label: '填报人'
        },
        {
          keyName: 'fillerDate',
          type: 'a-date-picker',
          disabled: true,
          label: '填报时间',
          attrs: {
            valueFormat: 'YYYY-MM-DD'
          }
        },
        {
          type: Selector,
          keyName: 'planTypeId',
          viewName: 'planTypeName',
          label: '方案类别',
          attrs: {
            selectType: '41'
          }
        },
        {
          keyName: 'textPage',
          type: 'BaseInputNumber',
          label: '正文页数',
          precision: 0,
          attrs: {
            min: 1
          }
        },
        {
          keyName: 'attachPage',
          type: 'BaseInputNumber',
          label: '附页页数',
          precision: 0,
          attrs: {
            min: 1
          }
        },
        {
          keyName: 'describes',
          label: '版本描述',
          type: 'BaseTextarea',
          autoSize: { minRows: 10, maxRows: 10 },
          attrs: {
            maxLength: 3000
          },
          ellipsis: true,
          span: 24
        }
      ]
    }
  },
  watch: {
    // 监听方案类型重新初始化
    '$route.query.programmeType': {
      immediate: true,
      async handler(e) {
        this.programmeType = e
        this.editModel = this.$route.query?.editModel || 0
        this.businessId = this.$route.query?.businessId
        this.historyId = this.$route.query?.historyId
        this.id = this.$route.query?.id
        this.programmeType && (this.editModel || this.editModel == 0) && this.$nextTick(this.init)
        if(e){
          let processConfigKey = this.getPriceByName(e)
          //获取通过获取流程配置值
          this.processConfig = await this.$getConfigFn(processConfigKey)
        }
      }
    }
  },
  methods: {
     getPriceByName (name){
      const foodMap = {
        '1': 'quality_actual_plan',
        '2': 'quality_sample_lead_plan',
        '3':'quality_six_aut_governance_plan',
      }
    return foodMap[ name ]
  },

    selectOrg(val) {
      this.form.branchComId = val[val.length - 2].orgId
      this.form.projectId = val[val.length - 1].projectId
    },
    getAuditProjectList(val) {
      this.form.editEmployee = ""
        this.projectDeptId = val.projectDeptOrgId
        this.$forceUpdate()
    },
    /**
     * @description: 初始化
     */
    init() {
      // 若有审批类型，则是审批查看，映射方案类型
      if (this.businessType) {
        this.programmeType = { 412: 1, 413: 2, 414: 3 }[this.businessType]
      }
      // 映射标题
      this.$route.meta.title =
        ['实测实量方案', '样板引路实施方案', '品质工程六项措施方案'][this.programmeType - 1] +
        ['查看', '编辑', '新增', '调整'][this.editModel]
      // 不为添加时请求详情
      if (this.editModel != 2) {
        this.loading.DRAFT = true
        let args = {
          planType: this.programmeType // 0：实测实量方案；1：样板引路实施方案；2：编制品质工程六项专项治理方案
        }
        // 若业务id存在，则说明是审批查看详情
        if (this.businessId) {
          args.id = this.businessId
        } else {
          args.id = this.id
        }
        // 若历史id存在，则说明是查看历史详情
        this.historyId && (args.historyId = this.historyId)
        args.id &&
          planBusinessBase
            .getDetail(args)
            .then((res) => {
              this.loading.DRAFT = false
              if (res.code === 200) {
                res.data.planTypeId = res.data.planType?.id
                res.data.planTypeName = res.data.planType?.name
                // 若文件不存在则设置空数组
                !res.data.fileArrays && (res.data.fileArrays = [])
                this.form = res.data
                this.form.branchPname = this.form.branchComName + '/' + this.form.projectName
                this.statusCode = res.data.status // 审批状态
                this.$nextTick(() => {
                  if (this.editModel != 0) {
                    this.form.filler = JSON.parse(sessionStorage.getItem('ycloud-user_info'))?.name // 默认填报人
                    this.form.fillerDate = this.$dateFormat(new Date(), 'D') // 默认填报时间
                  }
                  res.data.editEmployeeId &&
                    res.data.editName &&
                    this.$set(this.form, 'editEmployee', {
                      key: res.data.editEmployeeId,
                      label: res.data.editName
                    })
                })
              }
            })
            .catch(() => {
              this.loading.DRAFT = false
            })
      } else {
        this.form = {}
        this.form.filler = JSON.parse(sessionStorage.getItem('ycloud-user_info'))?.name // 默认填报人
        this.form.fillerDate = this.$dateFormat(new Date(), 'D') // 默认填报时间
      }
    },
    /**
     * @description: 提交表单
     * @param {String} statusCode：提交状态：[ 草稿：DRAFT,审批中：SUBMITTED]
     */
    handleSubmit(statusCode) {
     this.setProcessConfig = null;
      let that = this
      let name = ['update', 'create', 'adjustment'][that.editModel - 1] // 根据操作切换url地址
      const submit = () => {
        let form = that.$clone(that.form)
        // 添加审批状态
        form.status = that.statusCode == 'REJECTED' && statusCode === 'DRAFT' ? that.statusCode : statusCode
        // 添加方案类型
        form.planType = that.programmeType
        // 格式化文件列表
        form.fileLists = form.fileArrays?.map((i) => i.commonId) || []
        // 删除多余参数
        delete form.fileArrays
        // 删除多余参数
        delete form.editEmployee
        that.loading[statusCode] = true
        // 提交表单
        planBusinessBase[name](form)
          .then((res) => {
            if (res.code === 200 || res.data.code === 200) {
              that.loading[statusCode] = false
              that.$message.success((statusCode === 'DRAFT' ? '保存' : '提交') + '成功！')
              if(statusCode =='SUBMITTED') {
                //提交时，返回id
                    that.businessId = res.data.id;
                    that.setProcessConfig = this.processConfig;
                    return
                }else{
                  that.$multiTab.close()
                 }
            }
          })
          .catch(() => {
            that.loading[statusCode] = false
          })
      } // 提交表单

      // 若是草稿则无需校验表单
      if (statusCode === 'DRAFT') {
        submit()
        return
      }
      // 校验表单
      that.$refs.ruleForm.validate((e) => {
        if(e) {
          this.submitApprovalConfirm(this.processConfig, (flag)=>{
            if(!flag) {
              return
            }
            submit()
          })
        } else {
          this.$message.warning("请填写完所有必填项信息")
        }
      })
    }
  }
}
</script>
